//
//  DiscoveryViewController.swift
//  u17Comic
//
//  Created by hujian on 2019/7/9.
//  Copyright © 2019 hujian. All rights reserved.
//

import UIKit


class DiscoveryViewController: BaseViewController,UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    private var curOffY:CGFloat = 0.0
    private var galleryItems = [GalleryItemModel]()
    private var comicLists = [Modules]()
    private let BannerHeaderCellIdentifier = "BannerHeaderCell"
    private let AlcrossRecommendCellIdentifier = "AlcrossRecommendCell"
    private let CollectionHeaderIdentifier = "HJCollectionHeaderIdentifier"
    private let CollectionFooterIdentifier = "HJCollectionFooterIdentifier"
    private let U17RecommendHeaderViewIdentifier = "U17RecommendHeaderView"
    private let U17FooterViewIdentifier = "U17FooterView"
    
    private lazy var topView: TopNavView = {
        let view: TopNavView = TopNavView.init(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 120))
        view.keyword = "降龙"
        return view
    }()
    
    private lazy var navigationBarY: CGFloat = {
        return navigationController?.navigationBar.frame.maxY ?? 0
    }()
    
//    private lazy var emptyView: UEmptyView = {
//        let view = UEmptyView(verticalOffset: 300){self.requestData() }
//        view.allowShow = true
//        return view
//    }()
    
    lazy var collectionView :UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        let collection = UICollectionView.init(frame: CGRect(x:0, y: 0 ,width: 0, height:0), collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        collection.backgroundColor = UIColor.white
        collection.register(HeaderColCell.self, forCellWithReuseIdentifier: BannerHeaderCellIdentifier)
        collection.register(UINib.init(nibName: "AlcrossRecommendCell", bundle: nil), forCellWithReuseIdentifier: AlcrossRecommendCellIdentifier)
        collection.register(U17RecommendHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: U17RecommendHeaderViewIdentifier)
        collection.register(U17FooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: U17FooterViewIdentifier)
        
        
        collection.uHead = URefreshHeader { [weak self] in self?.requestData() }
        collection.uFoot = URefreshDiscoverFooter()
        collection.uempty = UEmptyView(verticalOffset: -10){self.requestData() }
        return collection
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.lightGray
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        view.addSubview(topView)
//        collectionView.parallaxHeader.view = bannerView
//        collectionView.parallaxHeader.height = navigationBarY + 300
//        collectionView.parallaxHeader.minimumHeight = navigationBarY
//        collectionView.parallaxHeader.mode = .bottom
        requestData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    
    
    //MARK:- 网络请求
    private func requestData(){
        ApiLoadingProvider.request(UApi.discovery, model: DiscoveryModel.self) { [weak self] (returnData) in
            self?.galleryItems = returnData?.galleryItems ?? []
            self?.comicLists = returnData?.modules ?? []

            self?.collectionView.uHead.endRefreshing()
            self?.collectionView.uempty?.allowShow = true

            self?.collectionView.reloadData()
//            self?.bannerView.imagePaths = self?.galleryItems.filter { $0.cover != nil }.map { $0.cover! } ?? []
        }
    }
    
    private func didSelectBanner(index: NSInteger) {
        let item = galleryItems[index]
//        if item.linkType == 2 {
//            guard let url = item.ext?.compactMap({ return $0.key == "url" ? $0.val : nil }).joined() else { return }
//            let vc = UWebViewController(url: url)
//            navigationController?.pushViewController(vc, animated: true)
//        } else {
//            guard let comicIdString = item.ext?.compactMap({ return $0.key == "comicId" ? $0.val : nil }).joined(),
//                let comicId = Int(comicIdString) else { return }
//            let vc = UComicViewController(comicid: comicId)
//            navigationController?.pushViewController(vc, animated: true)
//        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offY = scrollView.contentOffset.y
        topView.offY = offY
        curOffY = offY
        setNeedsStatusBarAppearanceUpdate()
        print("offY:  \(offY)")
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        if curOffY > 100 {
            return .default
        } else {
            return .lightContent
        }
    }
}

//MARK:-uicollectionview设置
extension DiscoveryViewController {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if galleryItems.count == 0 {
            return 0
        }
        return comicLists.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        if section == 0 {
//            return 1
//        }else if section == 1 || section == 2 || section == 3{
//            return 4
//        }else if section == 4 || section == 6 || section == 8 || section == 9 || section == 10{
//            return 3
//        }else {
//            return 2
//        }
        if section == 0 {
            if galleryItems.count == 0 {
                return 0
            }
            return 1
        } else {
            let module = comicLists[section - 1]
            return module.items?.count ?? 0
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BannerHeaderCellIdentifier, for: indexPath) as! HeaderColCell
            let arr = self.galleryItems.filter { $0.cover != nil }.map { $0.cover! }
            cell.bannerView.imagePaths = arr
            return cell
        } else {
            let comicList = comicLists[indexPath.section - 1]
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AlcrossRecommendCellIdentifier, for: indexPath) as! AlcrossRecommendCell
            let arr = comicList.items?[indexPath.item]
            cell.model = arr?.first
            cell.backgroundColor = UIColor.white
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            return
        }else {

        }
    }
    
    //每个分区的内边距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    //最小 item 间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 6;
    }
    
    //最小行间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 6;
    }
    
    //item 的尺寸
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        if  indexPath.section == 0{
//            return CGSize.init(width:ScreenWidth,height:260)
//        }else if indexPath.section == 1 || indexPath.section == 2 {
//            return CGSize.init(width:ScreenWidth/2-3,height:150)
//        }else if indexPath.section == 3{
//            return CGSize.init(width:ScreenWidth/2-3,height:120)
//        }else if indexPath.section == 4 || indexPath.section == 6 || indexPath.section == 9 || indexPath.section == 10{
//            return CGSize.init(width:ScreenWidth/3-4,height:220)
//        }else if indexPath.section == 8{
//            return .zero
//        }else {
//            return CGSize.init(width:ScreenWidth/2-3,height:150)
//        }
        if  indexPath.section == 0{
            return CGSize.init(width:ScreenWidth,height:350)
        } else {
            return CGSize.init(width:ScreenWidth/2-3,height:150)
        }
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSize.zero
        }else {
            return CGSize.init(width: ScreenHeight, height:40)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: ScreenWidth, height: 10.0)
    }
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        if kind == UICollectionView.elementKindSectionHeader {
//            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionHeaderIdentifier, for: indexPath)
//            return headerView;
//        } else {
//            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionFooterIdentifier, for: indexPath)
//            return footer;
//        }
//
//    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView : U17RecommendHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: U17RecommendHeaderViewIdentifier, for: indexPath) as! U17RecommendHeaderView
            let comicList:Modules = comicLists[indexPath.section - 1]
            let title = comicList.moduleInfo?.title
            if ( title != nil) {
                headerView.titleL.text = title
                headerView.imageView.kf.setImage(with:URL(string:(comicList.moduleInfo?.icon!)!))
            }
            // 每个分区header右侧点击更多按钮
//            headerView.headerMoreBtnClick = {[weak self]() in
//                if indexPath.section == 3 {
//
//                }else if indexPath.section == 5 {
//
//                }else if indexPath.section == 7 {
//                    let vc = U17WebViewController(url: "http://m.u17.com/wap/cartoon/list")
//                    vc.title = "动画"
//                    self?.navigationController?.pushViewController(vc, animated: true)
//                }else {
//                    let comicList:ComicListModel = (self?.comicLists[indexPath.section])!
//                    let vc = U17MoreBooksController(argCon: comicList.argCon,
//                                                    argName:comicList.argName,
//                                                    argValue:comicList.argValue)
//                    vc.title = comicList.itemTitle
//                    self?.navigationController?.pushViewController(vc, animated: true)
//                }
//            }
            return headerView
        }else if kind == UICollectionView.elementKindSectionFooter {
            let footerView : U17FooterView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: U17FooterViewIdentifier, for: indexPath) as! U17FooterView
            return footerView
        }
        return UICollectionReusableView()
    }
}
